testing - vitest

2024-02-12

Testing. Testing is not only a good way to make sure your code does what you expect (and alerts you when something goes wrong), but works as documentation as well.

So, how do we test stuff? Well, there are plenty of testing frameworks, I've personally used Jest (now open source) and Testing Library (formerly React Testing Library) when working with React. This time around I got to take Vitest for a spin. Not too different from Jest, considering it mimics API, makes sense.

So why Vitest? Well, I was using Vite during a refresher course and why not stay within the same universe 🤷🏻‍♀️.

With this, I used Happy DOM, apparently a lighter alternative to JSDOM.

Something interesting here, the folder that takes the tests is called __tests__. Something, upto this point, I had only seen within the Python universe. Fun fact: apparently, those double underscores are called "dunders". More importantly the naming does have significance as Vitest will assume all files inside there are tests.

As for your package.json, another fun fact, having a test cmd under scripts, will allow you to run it with just npm t instead of npm run test.

Inside vite.config.js:

test: {
  environment: "happy-dom",
},

When grabbing elements for testing, make use of data-testid attr, this keeps things decoupled and tidy.

UI interaction tests, if user does X, we expect Y. These are nice as they document a user story.

Testing custom hooks: renderHook. This abstracts creating a component running the hook lifecycle.

Testing requests without actually hitting API: vitest-fetch-mock. SN: For doing alot of fake API calls, one may generate an OpenAPI spec and use that to generate a fake API.

Snapshots, these types of tests are seen as low confidence . However, may be useful for something one expects to never change and would be problematic if it did. For example: on a homepage, I actually was part of a project where certain things needed to be there and stay that way. As with all things, depends on the situation, use best judgement. Lastly, if you do have snapshots, they are meant to be commited.

Coverage, this is where you see how much of your code is covered by tests. There's an interactive viewer you can see what is/isnt covered.

vitest - vsCode extension

Some thoughts shared on testing:

  • Try to test for functionality, not implementation.
  • Make your tests interact with things as user would, not as a dev.
    • There are exceptions, of course, depending on circumstance.
  • Don't be afraid to delete tests.
    • Fix or delete, poo tests are useless tests.
  • Catching bugs: write a failing test vefore fixing that way once fixed you can have some confidence in regards to regressions.

← go back